package com.yanqu.manager;

import com.yanqu.dao.HistoryGoodsGetDataDaoImpl;
import com.yanqu.dao.UserGoodsGetDataDaoImpl;
import com.yanqu.data.entity.GoodsGet;
import com.yanqu.data.entity.HistoryGoodsGetData;
import com.yanqu.data.entity.LogGoodsEntity;
import com.yanqu.data.entity.UserGoodsGetData;
import com.yanqu.data.entity.setting.CustomGoodsBaseValueData;
import com.yanqu.data.entity.setting.CustomThresholdRatioData;
import com.yanqu.data.entity.setting.GoodsIgnoreData;
import com.yanqu.road.entity.enums.eChannelType;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author wangmingming
 * 道具获得监控
 * 玩家数据--->汇总每日最大
 * 每日最大--->汇总今日基准
 */
public class UserGetGoodsMonitorMgr extends TempMgr {

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {

        int todayZeroTime = (int)(DateHelper.getZeroTimeStamp(System.currentTimeMillis()) / 1000);
        int beginTime = todayZeroTime - (int)DateHelper.DAY_SECONDS * 180;
        historyMaxId = new AtomicLong(new HistoryGoodsGetDataDaoImpl().getMaxHistoryId());
        userGoodsGetDataMap = new UserGoodsGetDataDaoImpl().getUserGoodsGetData();
        historyMaxDataMap = new HistoryGoodsGetDataDaoImpl().getHistoryGoodsGetData(beginTime);
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    private static final Logger logger = LogManager.getLogger(UserGetGoodsMonitorMgr.class.getName());

    /**
     * 需要监控的最小值
     * 可以设置
     */
    private static long MIN_MONITOR_VALUE = 50L;

    /**
     * 递增的告警阈值
     * 可以设置
     */
    private static long ALARM_INC = 500L;

    /**
     * 历史数据最大的id
     */
    private static AtomicLong historyMaxId = new AtomicLong(0);

    /**
     * 基准值(每日统计一次，历史最高),按途径维度取最高
     * 缓存
     * day,vip,way
     */
//    private static Map<Integer, Map<Integer, Map<Integer, List<HistoryGoodsGetData>>>> baseValueDataMap = new ConcurrentHashMap<>();

    /**
     * 基准值(每日统计一次，历史最高)，按道具，取最高的途径作为其他途径的最高
     * 缓存,只缓存每个道具最高的way
     * day,vip,goodId
     */
    private static Map<Integer, Map<Integer, Map<Integer, HistoryGoodsGetData>>> baseValueDataMapV2 = new ConcurrentHashMap<>();

    /**
     * 每日最大值（实时）统计。多一层减少遍历list的数量级
     * 需要持久化
     * day,vip,way
     */
    private static Map<Integer, Map<Integer, Map<Integer, List<HistoryGoodsGetData>>>> historyMaxDataMap = new ConcurrentHashMap<>();

    /**
     * 玩家实时获取情况
     * 需要持久化
     * userId
     */
    private static Map<Long, UserGoodsGetData> userGoodsGetDataMap = new ConcurrentHashMap<>();

    /**
     * 有变更的玩家
     */
    private static Set<Long> changeUserSet = new HashSet<>();

    /**
     * 保存
     */
    @Override
    public boolean save(){
        for (Map.Entry<Long, UserGoodsGetData> entry : userGoodsGetDataMap.entrySet()) {
            UserGoodsGetData value = entry.getValue();
            if(value.isInsertOption()){
                new UserGoodsGetDataDaoImpl().add(value);
            }else if(value.isUpdateOption()){
                new UserGoodsGetDataDaoImpl().update(value);
            }
        }


        for (Map.Entry<Integer, Map<Integer, Map<Integer, List<HistoryGoodsGetData>>>> entry : historyMaxDataMap.entrySet()) {
            for (Map.Entry<Integer, Map<Integer, List<HistoryGoodsGetData>>> mapEntry : entry.getValue().entrySet()) {
                for (Map.Entry<Integer, List<HistoryGoodsGetData>> listEntry : mapEntry.getValue().entrySet()) {
                    List<HistoryGoodsGetData> dataList = listEntry.getValue();
                    for (int i = 0; i < dataList.size(); i++) {
                        HistoryGoodsGetData data = dataList.get(i);
                        if(data.isInsertOption()){
                            new HistoryGoodsGetDataDaoImpl().add(data);
                        }else if(data.isUpdateOption()){
                            new HistoryGoodsGetDataDaoImpl().update(data);
                        }
                    }
                }
            }
        }

        int todayZeroTime = (int)(DateHelper.getZeroTimeStamp(System.currentTimeMillis()) / 1000);
        int removeZeroTime = todayZeroTime - 180 * (int)DateHelper.DAY_SECONDS;
        List<Integer> removeList = new ArrayList<>();
        for (Map.Entry<Integer, Map<Integer, Map<Integer, List<HistoryGoodsGetData>>>> entry : historyMaxDataMap.entrySet()) {
            if(entry.getKey() < removeZeroTime){
                removeList.add(entry.getKey());
            }
        }
        for (Integer time : removeList) {
            historyMaxDataMap.remove(time);
            getLogger().error("移除过期数据 {}", time);
        }
        return true;
    }

    /**
     * 记录玩家获取
     * @param logGoodsEntity 道具获取情况
     */
    public static void recordLogGoodsEntity(LogGoodsEntity logGoodsEntity){

        if(logGoodsEntity == null){
            return;
        }
        long userId = logGoodsEntity.getUserId();
        if(userId <= 0){
            return;
        }
        if(logGoodsEntity.getTime() == null){
            return;
        }
        if(logGoodsEntity.getGoodsId() <= 0 || logGoodsEntity.getNum() <= 0 || logGoodsEntity.getWay() <= 0){
            return;
        }
        if(logGoodsEntity.getVipExp() < 0){
            return;
        }
        int zeroTimeStamp = (int)(DateHelper.getZeroTimeStamp(logGoodsEntity.getTime().getTime()) / 1000);
        UserGoodsGetData userGoodsGetData = userGoodsGetDataMap.get(userId);
        if(userGoodsGetData == null){
            synchronized (getUserLocker(userId)){
                userGoodsGetData = userGoodsGetDataMap.get(userId);
                if(userGoodsGetData == null){
                    userGoodsGetData = new UserGoodsGetData();
                    userGoodsGetData.setUserId(userId);
                    userGoodsGetData.setGoodsGetListMap(new ConcurrentHashMap<>());
                    userGoodsGetData.setInsertOption();
                    userGoodsGetDataMap.put(userId, userGoodsGetData);
                }
            }
        }

        GoodsGet target = null;
        synchronized (getUserLocker(userId)){
            userGoodsGetData.setVip(getVipLv(logGoodsEntity.getVipExp()));
            if(!userGoodsGetData.getGoodsGetListMap().containsKey(zeroTimeStamp)){
                userGoodsGetData.getGoodsGetListMap().put(zeroTimeStamp, new ArrayList<>());
            }
            List<GoodsGet> goodsGetList = userGoodsGetData.getGoodsGetListMap().get(zeroTimeStamp);
            for (int i = 0; i < goodsGetList.size(); i++) {
                GoodsGet goodsGet = goodsGetList.get(i);
                if(goodsGet.getW() == logGoodsEntity.getWay() && goodsGet.getG() == logGoodsEntity.getGoodsId()){
                    target = goodsGet;
                    break;
                }
            }
            if(target == null){
                target = new GoodsGet();
                target.setG(logGoodsEntity.getGoodsId());
                target.setW(logGoodsEntity.getWay());
                goodsGetList.add(target);
            }
            target.setT(target.getT() + 1);
            target.setN(target.getN() + logGoodsEntity.getNum());
            userGoodsGetData.setUpdateOption();
        }

        //今日最大值比较
        todayMaxValueRank(zeroTimeStamp, userGoodsGetData, target);

        synchronized (changeUserSet){
            changeUserSet.add(userId);
        }
    }

    public static void todayMaxValueRank(int zeroTimeStamp, UserGoodsGetData userGoodsGetData, GoodsGet target) {

        Map<Integer, Map<Integer, List<HistoryGoodsGetData>>> todayVipMap = historyMaxDataMap.get(zeroTimeStamp);
        if(todayVipMap == null){
            synchronized (historyMaxDataMap){
                todayVipMap = historyMaxDataMap.get(zeroTimeStamp);
                if(todayVipMap == null){
                    todayVipMap = new ConcurrentHashMap<>();
                    historyMaxDataMap.put(zeroTimeStamp, todayVipMap);
                }
            }
        }

        Map<Integer, List<HistoryGoodsGetData>> todayWayMap = todayVipMap.get(userGoodsGetData.getVip());
        if(todayWayMap == null){
            synchronized (todayVipMap){
                todayWayMap = todayVipMap.get(zeroTimeStamp);
                if(todayWayMap == null){
                    todayWayMap = new ConcurrentHashMap<>();
                    todayVipMap.put(userGoodsGetData.getVip(), todayWayMap);
                }
            }
        }

        List<HistoryGoodsGetData> historyGoodsGetDataList = todayWayMap.get(target.getW());
        if(historyGoodsGetDataList == null){
            synchronized (todayWayMap){
                historyGoodsGetDataList = todayWayMap.get(target.getW());
                if(historyGoodsGetDataList == null){
                    historyGoodsGetDataList = new ArrayList<>();
                    todayWayMap.put(target.getW(), historyGoodsGetDataList);
                }
            }
        }

        synchronized (historyGoodsGetDataList){
            HistoryGoodsGetData historyGoodsGetData = null;
            for (HistoryGoodsGetData goodsGetData : historyGoodsGetDataList) {
                if(goodsGetData.getGoodsId() == target.getG() && goodsGetData.getWay() == target.getW()){
                    historyGoodsGetData = goodsGetData;
                    break;
                }
            }
            if(historyGoodsGetData != null){
                if(target.getN() > historyGoodsGetData.getMaxNum()){
                    historyGoodsGetData.setMaxNum(target.getN());
                    historyGoodsGetData.setMaxNumUser(userGoodsGetData.getUserId());
                }
                if(target.getT() > historyGoodsGetData.getMaxTimes()){
                    historyGoodsGetData.setMaxTimes(target.getT());
                    historyGoodsGetData.setMaxTimesUser(userGoodsGetData.getUserId());
                }
            }else {
                historyGoodsGetData = new HistoryGoodsGetData();
                historyGoodsGetData.setDbId(historyMaxId.incrementAndGet());
                historyGoodsGetData.setVip(userGoodsGetData.getVip());
                historyGoodsGetData.setWay(target.getW());
                historyGoodsGetData.setGoodsId(target.getG());
                historyGoodsGetData.setDayTime(zeroTimeStamp);
                historyGoodsGetData.setMaxNum(target.getN());
                historyGoodsGetData.setMaxNumUser(userGoodsGetData.getUserId());
                historyGoodsGetData.setMaxTimes(target.getT());
                historyGoodsGetData.setMaxTimesUser(userGoodsGetData.getUserId());
                historyGoodsGetData.setInsertOption();
                historyGoodsGetDataList.add(historyGoodsGetData);
            }
        }
    }

    /**
     * 每日统计（每20秒）
     */
    public static void dayReset(){

        int todayZeroTime = (int)(DateHelper.getZeroTimeStamp(System.currentTimeMillis()) / 1000);

        //移除过期的基准
        int removeZeroTime = todayZeroTime - 2 * (int)DateHelper.DAY_SECONDS;
        List<Integer> removeKeyList = new ArrayList<>();
        for (Integer key : baseValueDataMapV2.keySet()) {
            if(key <= removeZeroTime){
                removeKeyList.add(key);
            }
        }
        for (Integer key : removeKeyList) {
            baseValueDataMapV2.remove(key);
        }

        //今日基准已生成
        if(baseValueDataMapV2.containsKey(todayZeroTime)){
            return;
        }

        reCalDayBaseValue(todayZeroTime);

    }

    public static void reCalDayBaseValue(int todayZeroTime) {

        //昨日做为起始时间
        List<Integer> timeLineList = new ArrayList<>();
        int yesterdayZeroTime = todayZeroTime - (int) DateHelper.DAY_SECONDS;
        timeLineList.add(yesterdayZeroTime);
        //过去180天
        for (int i = 1; i < 180; i++) {
            timeLineList.add(yesterdayZeroTime - i * (int)DateHelper.DAY_SECONDS);
        }

        logger.info("开始计算 {} 的基准值", todayZeroTime);

        //统计过去180天的最大值
        //vip,goodId
        Map<Integer, Map<Integer, HistoryGoodsGetData>> tempBaseValueMap = new ConcurrentHashMap<>();

        for (Integer zeroTime : timeLineList) {
            Map<Integer, Map<Integer, List<HistoryGoodsGetData>>> benchmarkMap = historyMaxDataMap.get(zeroTime);
            if(benchmarkMap == null){
                continue;
            }
            for (Map.Entry<Integer, Map<Integer, List<HistoryGoodsGetData>>> entry : benchmarkMap.entrySet()) {
                int vip = entry.getKey();
                if(!tempBaseValueMap.containsKey(vip)){
                    tempBaseValueMap.put(vip, new ConcurrentHashMap<>());
                }

                for (Map.Entry<Integer, List<HistoryGoodsGetData>> listEntry : entry.getValue().entrySet()) {
                    int way = listEntry.getKey(); //忽略途径

                    List<HistoryGoodsGetData> historyGoodsGetDataList = listEntry.getValue();
                    for (HistoryGoodsGetData history : historyGoodsGetDataList) {

                        HistoryGoodsGetData tempBaseValue = tempBaseValueMap.get(vip).get(history.getGoodsId());

                        if(tempBaseValue != null){
                            if(history.getMaxNum() > tempBaseValue.getMaxNum()){
                                tempBaseValue.setMaxNum(history.getMaxNum());
                                tempBaseValue.setMaxNumUser(history.getMaxNumUser());
                            }
                            if(history.getMaxTimes() > tempBaseValue.getMaxTimes()){
                                tempBaseValue.setMaxTimes(history.getMaxTimes());
                                tempBaseValue.setMaxTimesUser(history.getMaxTimesUser());
                            }
                        }else {
                            tempBaseValue = new HistoryGoodsGetData();
                            tempBaseValue.setDbId(history.getDbId());
                            tempBaseValue.setVip(history.getVip());
                            tempBaseValue.setWay(history.getWay());
                            tempBaseValue.setGoodsId(history.getGoodsId());
                            tempBaseValue.setDayTime(todayZeroTime);
                            tempBaseValue.setMaxNum(history.getMaxNum());
                            tempBaseValue.setMaxNumUser(history.getMaxNumUser());
                            tempBaseValue.setMaxTimes(history.getMaxTimes());
                            tempBaseValue.setMaxTimesUser(history.getMaxTimesUser());
                            tempBaseValueMap.get(vip).put(tempBaseValue.getGoodsId(), tempBaseValue);
                        }
                    }
                }
            }
        }

        //直接用设定的来覆盖
        for (Map.Entry<Integer, Map<Integer, Map<Integer, CustomGoodsBaseValueData>>> entry : UserGoodsMonitorSettingMgr.getCustomBaseValueMap().entrySet()) {
            if(entry.getKey() != 0){
                continue;
            }
            //如果有设定的阈值，则覆盖历史基准，只会用通用的设置来覆盖
            for (Map.Entry<Integer, Map<Integer, CustomGoodsBaseValueData>> mapEntry : entry.getValue().entrySet()) {
                int vip = mapEntry.getKey();
                if(!tempBaseValueMap.containsKey(vip)){
                    tempBaseValueMap.put(vip, new ConcurrentHashMap<>());
                }
                for (Map.Entry<Integer, CustomGoodsBaseValueData> dataEntry : mapEntry.getValue().entrySet()) {
                    int goods = dataEntry.getKey();
                    HistoryGoodsGetData tempBaseValue = new HistoryGoodsGetData();
                    tempBaseValue.setDbId(0);
                    tempBaseValue.setVip(vip);
                    tempBaseValue.setWay(0);
                    tempBaseValue.setGoodsId(goods);
                    tempBaseValue.setDayTime(todayZeroTime);
                    tempBaseValue.setMaxNum(dataEntry.getValue().getMaxNum());
                    tempBaseValue.setMaxNumUser(0);
                    tempBaseValue.setMaxTimes(dataEntry.getValue().getMaxTimes());
                    tempBaseValue.setMaxTimesUser(0);

                    tempBaseValueMap.get(vip).put(goods, tempBaseValue);
                }
            }
        }

        if(tempBaseValueMap.size() > 0){
            //统一计算阈值，modify by 20241201
//            for (Map.Entry<Integer, Map<Integer, HistoryGoodsGetData>> entry : tempBaseValueMap.entrySet()) {
//                int vip = entry.getKey();
//                for (Map.Entry<Integer, HistoryGoodsGetData> dataEntry : entry.getValue().entrySet()) {
//                    int goodsId = dataEntry.getKey();
//                    HistoryGoodsGetData data = dataEntry.getValue();
//                    long beiLv = getBeiLvByNum(vip, goodsId, data.getMaxNum(), 1);
//                    long maxNumAfterRatio = BigDecimal.valueOf(data.getMaxNum()).multiply(BigDecimal.valueOf(beiLv)).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_UP).longValue();
//                    data.setMaxNumAfterRatio(maxNumAfterRatio);
//
//                    beiLv = getBeiLvByNum(vip, goodsId, data.getMaxNum(), 0);
//                    long maxTimesAfterRatio = BigDecimal.valueOf(data.getMaxNum()).multiply(BigDecimal.valueOf(beiLv)).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_UP).longValue();
//                    data.setMaxTimesAfterRatio(maxTimesAfterRatio);
//                }
//            }

            baseValueDataMapV2.put(todayZeroTime, tempBaseValueMap);
            logger.info("结束计算 {} 的基准值", todayZeroTime);
        }
    }

    /**
     * 实时计算(每分钟)
     */
    public static void benchmark(){

        Set<Long> userSet = null;
        synchronized (changeUserSet){
            if(changeUserSet.size() > 0){
                userSet = new HashSet<>(changeUserSet);
                changeUserSet.clear();
            }
        }

        int todayZeroTime = (int)(DateHelper.getZeroTimeStamp(System.currentTimeMillis()) / 1000);

        if(userSet != null){
            for (Long userId : userSet) {


                UserGoodsGetData userGoodsGetData = userGoodsGetDataMap.get(userId);
                if(userGoodsGetData == null){
                    continue;
                }

                List<GoodsGet> goodsGetList = userGoodsGetData.getGoodsGetListMap().get(todayZeroTime);
                if(goodsGetList == null){
                    continue;
                }

                boolean change = false;
                //阈值=参考值*倍率
//                long beiLv = 2000;  //千分比
                //每个道具都要比较
                int channelId = 0;
                String channelName = "";
                try{
                    String substring = String.valueOf(userId).substring(0, 3);
                    channelId = Integer.parseInt(substring);
                    eChannelType channelType = eChannelType.forValue(channelId);
                    if(channelType != null){
                        channelName = channelType.getName();
                    }
                }catch (Exception e){
                    logger.error("", e);
                }
                for (int i = 0; i < goodsGetList.size(); i++) {
                    GoodsGet goodsGet = goodsGetList.get(i);

                    //过滤道具白名单
                    if(UserGoodsMonitorSettingMgr.isGoodsIgnore(channelId, goodsGet.getG()) || UserGoodsMonitorSettingMgr.isGoodsIgnore(0, goodsGet.getG())){
                        //白名单，不统计
                        continue;
                    }

                    //历史计算的基准值(包括后台设置的渠道0的通用值)
                    HistoryGoodsGetData baseValue = getBaseValueV2(todayZeroTime, userGoodsGetData.getVip(), goodsGet.getG());
                    if(baseValue == null){
                        //查新特定渠道有沒有基准值
                        CustomGoodsBaseValueData customGoodsBaseValueData = UserGoodsMonitorSettingMgr.getCustomGoodsBaseValueData(channelId, userGoodsGetData.getVip(), goodsGet.getG());
                        if(customGoodsBaseValueData != null && customGoodsBaseValueData.getDeleted() == 0){
                            baseValue = new HistoryGoodsGetData();
                            baseValue.setMaxNum(customGoodsBaseValueData.getMaxNum());
                            baseValue.setMaxTimes(customGoodsBaseValueData.getMaxTimes());
                            baseValue.setGoodsId(customGoodsBaseValueData.getGoodsId());
                            baseValue.setVip(customGoodsBaseValueData.getVip());
                        }else {
                            continue;
                        }
                    }

                    long beiLv = getBeiLvByNum(channelId, userGoodsGetData.getVip(), goodsGet.getG(), baseValue.getMaxNum(), 1);
                    long maxNum = BigDecimal.valueOf(baseValue.getMaxNum()).multiply(BigDecimal.valueOf(beiLv)).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_UP).longValue();
                    long serverId = getUserServerId(userId);
                    if(goodsGet.getN() > goodsGet.getNn() + maxNum){
                        //获得数量告警
                        logger.error("【逻辑大区】{}|| 【区服】{} {}||【角色】{}|| 【vip等级】{}|| 【途径】{} {} || 【道具】{} {} || 【阈值类型】{} || 【阈值】{}|| 【今日累计值】{}|| 【今日触发告警次数】{}",
                                channelName, serverId, DictMgr.getServerName(serverId),
                                userId, baseValue.getVip(), goodsGet.getW(), DictMgr.getWayName(goodsGet.getW()), baseValue.getGoodsId(), DictMgr.getGoodsName(baseValue.getGoodsId()),
                                "数量", maxNum, goodsGet.getN(), goodsGet.getNn() / maxNum + 1);
                        goodsGet.setNn(goodsGet.getNn() + maxNum);
                        change = true;
                    }

                    beiLv = getBeiLvByNum(channelId, userGoodsGetData.getVip(), goodsGet.getG(), baseValue.getMaxTimes(), 0);
                    long maxTimes = BigDecimal.valueOf(baseValue.getMaxTimes()).multiply(BigDecimal.valueOf(beiLv)).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_UP).longValue();
                    if(goodsGet.getT() > goodsGet.getNt() + maxTimes){
                        //获得频率告警
                        logger.error("【逻辑大区】{}|| 【区服】{} {}||【角色】{}|| 【vip等级】{}|| 【途径】{} {}|| 【道具】{} {} || 【阈值类型】{}|| 【阈值】{}|| 【今日累计值】{}|| 【今日触发告警次数】{}",
                                channelName, serverId, DictMgr.getServerName(serverId),
                                userId, baseValue.getVip(), goodsGet.getW(), DictMgr.getWayName(goodsGet.getW()), baseValue.getGoodsId(), DictMgr.getGoodsName(baseValue.getGoodsId()),
                                "次数", maxTimes, goodsGet.getT(), goodsGet.getNt() / maxTimes + 1);
                        goodsGet.setNt(goodsGet.getNt() + maxTimes);
                        change = true;
                    }
                }

                if(change){
                    userGoodsGetData.setUpdateOption();
                }
            }
        }

    }

    public static HistoryGoodsGetData getBaseValueV2(int dayTime, int vip, int goodsId){
        Map<Integer, Map<Integer, HistoryGoodsGetData>> vipMap = baseValueDataMapV2.get(dayTime);
        if(vipMap == null){
            return null;
        }
        Map<Integer, HistoryGoodsGetData> goodsMap = vipMap.get(vip);
        if(goodsMap == null){
            return null;
        }
        return goodsMap.get(goodsId);
    }

//    private static HistoryGoodsGetData getBaseValue(int dayTime, int vip, int way, int goodsId){
//        Map<Integer, Map<Integer, List<HistoryGoodsGetData>>> vipMap = baseValueDataMap.get(dayTime);
//        if(vipMap == null){
//            return null;
//        }
//        Map<Integer, List<HistoryGoodsGetData>> wayMap = vipMap.get(vip);
//        if(wayMap == null){
//            return null;
//        }
//        List<HistoryGoodsGetData> dataList = wayMap.get(way);
//        if(dataList == null){
//            return null;
//        }
//        for (int i = 0; i < dataList.size(); i++) {
//            HistoryGoodsGetData getData = dataList.get(i);
//            if(getData.getGoodsId() == goodsId){
//                return getData;
//            }
//        }
//        return null;
//    }


    private static Map<Long, Object> userLockerMap = new ConcurrentHashMap<>();

    /**
     * 获得玩家锁，占用一点内存
     */
    public static Object getUserLocker(long userId){
        if(!userLockerMap.containsKey(userId)){
            synchronized (userLockerMap){
                if(!userLockerMap.containsKey(userId)){
                    userLockerMap.put(userId, new Object());
                }
            }
        }
        return userLockerMap.get(userId);
    }

    /**
     * 临时
     * 获得vip等级
     * @param vipExp vip经验
     */
    public static int getVipLv(long vipExp){
        int vip = 0;
        List<Long> list = StringUtils.stringToLongList("25,98,300,1000,3000,10000,30000,100000,200000,400000,800000,1300000,2000000,3200000,5000000", ",");
        for (int i = 0; i < list.size(); i++) {
            if(vipExp >= list.get(i)){
                vip = i + 1;
            }
        }
        return vip;
    }

    public void removeData() {
        int todayZeroTime = (int)(DateHelper.getZeroTimeStamp(System.currentTimeMillis()) / 1000);

        //移除过期的玩家数据
        int removeZeroTime = todayZeroTime - (int)DateHelper.DAY_SECONDS;

        for (Map.Entry<Long, UserGoodsGetData> entry : userGoodsGetDataMap.entrySet()) {
            UserGoodsGetData value = entry.getValue();
            List<GoodsGet> remove = value.getGoodsGetListMap().remove(removeZeroTime);
            if(remove != null){
                value.setUpdateOption();
            }
        }
    }

    public static long getUserServerId(long userId){
        long userServerId = 0;
        try {
            userServerId = Long.parseLong(String.valueOf(userId).substring(0, 8));
        }catch (Exception e){
            getLogger().info("userId {} exception", userId);
        }
        return userServerId;
    }

    /**
     * 按用户群、道具、数量，获得阈值的倍率
     * @param type 0次数阈值 1数量阈值
     */
    public static long getBeiLvByNum(int channelId, int vip, int goods, long num, int type){
        List<CustomThresholdRatioData> ratioDataList = UserGoodsMonitorSettingMgr.getCustomThresholdRatioData(channelId, vip, type);
        if(ratioDataList == null || ratioDataList.isEmpty()) {
            ratioDataList = UserGoodsMonitorSettingMgr.getCustomThresholdRatioData(0, vip, type);
        }
        if(ratioDataList == null || ratioDataList.isEmpty()) {
            return getBeiLvByNum(num, type);
        }
        for (CustomThresholdRatioData data : ratioDataList) {
            //比较区间，取值
            if(data.getThresholdRange().size() != 2){
                continue;
            }
            Integer min = data.getThresholdRange().get(0);
            if(min == null){
                min = Integer.MIN_VALUE;
            }
            Integer max = data.getThresholdRange().get(1);
            if(max == null){
                max = Integer.MAX_VALUE;
            }
            if(num >= min && num <= max){
                return data.getThresholdRatio();
            }
        }
        return getBeiLvByNum(num, type);
    }

    public static long getBeiLvByNum(long num, int type){
        if(num <= 2){
            return 10000;
        }
        if(num <= 10){
            return 5000;
        }
        if(num <= 100){
            return 3000;
        }
        return 2000;
    }
}
